var geocoder, map
var waypointById = {};
var markersArray = []; // store map markers so can do stuff with them later (ex. clear them)
var lat_string, lng_string, currentQuery, currAddress;

$(document).ready(function () {	
	geocoder = new google.maps.Geocoder();
	$("#search-form").submit(searchSubmit);

	// Currently, #map_canvas is only present on main page.
	// Thus, I am using its div tag to detect whether or to hook AJAX
	// functionality in, since we're not displaying search results via
	// AJAX from other pages.
	if ($("#map_canvas").length == 0)
		return;
	
	initializeMap();
	setMouseoverAnimations();
	activateWaypoints();
	$(".sort_criteria").click(sortBy);
	
	// If came from another page, these elements will not have been filled.
	
	if (window.location.search.substring(1).length > 0) {
		currentQuery = decodeURIComponent(getQueryVariableFromURL("query"));
		$("#id_query").val(currentQuery);
		$('#search_query').text(currentQuery);
	
		currAddress = decodeURIComponent(getQueryVariableFromURL("location"));
		$("#id_location").val(currAddress);
		$('#search_location').text(currAddress);
		
		lat_string = "&lat=" + decodeURIComponent(getQueryVariableFromURL("lat"));
		lng_string = "&lng=" + decodeURIComponent(getQueryVariableFromURL("lng"));
	}
});

function initializeMap() {
   var latlng = new google.maps.LatLng(40.7669792, -73.9845695);
   var myOptions = {
     zoom: 13,
     center: latlng,
     mapTypeId: google.maps.MapTypeId.ROADMAP
   };
   
   map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function setMouseoverAnimations() {
	$(".dish_info_container").mouseenter(function() {
		var dish_id = this.getElementsByClassName("maps_info")[0].getElementsByClassName("maps_info_dish_id")[0].textContent;
		var marker = waypointById[dish_id]['marker'];
		if (marker.getAnimation() == null)
			marker.setAnimation(google.maps.Animation.BOUNCE);
	}).mouseleave(function() {
		var dish_id = this.getElementsByClassName("maps_info")[0].getElementsByClassName("maps_info_dish_id")[0].textContent;
		var marker = waypointById[dish_id]['marker'];
		marker.setAnimation(null);
	});
}

function searchSubmit() {
	currentQuery = $("#id_query").val();
	currAddress = $("#id_location").val();
	geocoder.geocode( { 'address': currAddress }, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			lat_string = "&lat=" +results[0].geometry.location.lat();
			lng_string = "&lng=" + results[0].geometry.location.lng();
			var paramStrng = "query=" + encodeURIComponent(currentQuery) + lat_string + lng_string;
			if (map != null) {
				map.setCenter(results[0].geometry.location);
		 
				// for testing purposes only
				//$('#geo_results').text(results[0].geometry.location.toString());
				$('#search_query').text(currentQuery);
				$('#search_location').text(currAddress);
				$("#search_results").load("/search/?ajax&" + paramStrng, 
					function() {
						deleteOverlays();
						waypointById = {};
						activateWaypoints();
						setMouseoverAnimations();
					});
			}
			else {
				window.location = "/search/?" + paramStrng + "&location=" + currAddress;
			}
		} else {
	     alert("Geocode was not successful for the following reason: " + status);
		}
   });
   return false;
}

// get waypoint data from html - gotta be a better way to do this
function activateWaypoints() {
	$(".maps_info").each(function () {
		var dish_id, dish_name, lat, lng;
		jQuery.each(this.childNodes, function() {
			if (this.className == "maps_info_dish_name") {
				dish_name = this.textContent;
			}
			else if (this.className == "maps_info_dish_id") {
				dish_id = this.textContent;
			}
			else if (this.className == "maps_info_lat") {
				lat = this.textContent;
			}
			else if (this.className == "maps_info_lng") {
				lng = this.textContent;
			}
		});
		waypointById[dish_id] = {
			name: dish_name,
			lat: lat,
			lng: lng
		};
	});
	
	// populate map with markers
	for (dish_id in waypointById)
	{
		var lng = waypointById[dish_id]["lng"];
		var lat = waypointById[dish_id]["lat"];
		var marker = new google.maps.Marker({
			map: map,
			position: new google.maps.LatLng(lat, lng)
		});
		
		waypointById[dish_id]['marker'] = marker;
		markersArray.push(marker);
	}
}

function sortBy() {
	if (currentQuery === undefined || lat_string === undefined || lng_string === undefined)
		return;
	var criteria = this.textContent.toLowerCase();
	
	$("#search_results").load("/search/?ajax&query=" + encodeURIComponent(currentQuery) + lat_string + lng_string + "&sort_by=" + criteria, function () {setMouseoverAnimations()});

}

function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

function getQueryVariableFromURL(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  alert('Query Variable ' + variable + ' not found');
} 